using DG.Tweening;
using Toolkit.AudioExtend;
using UnityEngine;
using Utils;

namespace Managers
{
    public partial class GameManager
    {
        public ObservableValue<float> TimeScale { private set; get; }
        public ObservableValue<int> Quality { private set; get; }
        public ObservableValue<float> SoundEffectVolume { private set; get; }
        public ObservableValue<float> AudioVolume { private set; get; }

        private void Start()
        {
            TimeScale = new ObservableValue<float>(Time.timeScale)
                .WithValidator(value => Mathf.Clamp(value, 0f, 3f));
            TimeScale.OnValueChanged += TimeScaleChanged;

            Quality = new ObservableValue<int>(QualitySettings.GetQualityLevel());
            Quality.OnValueChanged += QualityOnOnValueChanged;

            SoundEffectVolume = new ObservableValue<float>(AudioManager.Singleton.SoundEffectPlayer.Volume);
            SoundEffectVolume.OnValueChanged += SoundEffectVolumeOnOnValueChanged;

            AudioVolume = new ObservableValue<float>(AudioManager.Singleton.AudioPlayer.Volume);
            AudioVolume.OnValueChanged += AudioVolumeOnOnValueChanged;
        }

        private float _lastTimeScale;

        /// <summary>
        /// 暂停游戏。
        /// </summary>
        public void Pause()
        {
            _lastTimeScale = TimeScale.Value;
            TimeScale.Value = 0;
        }

        /// <summary>
        /// 播放游戏。
        /// </summary>
        public void Play()
        {
            TimeScale.Value = _lastTimeScale;
        }

        /// <summary>
        /// 退出游戏。
        /// </summary>
        public void Quit()
        {
#if UNITY_EDITOR
            Debug.Log("退出游戏!!!");
#elif UNITY_WEBGL
            Web.WebHelper.Quit();
#elif UNITY_STANDALONE_WIN
            Application.Quit();
#endif
        }

        private void AudioVolumeOnOnValueChanged(float obj)
        {
            AudioManager.Singleton.AudioPlayer.Volume = obj;
        }

        private void SoundEffectVolumeOnOnValueChanged(float obj)
        {
            AudioManager.Singleton.SoundEffectPlayer.Volume = obj;
        }

        private void QualityOnOnValueChanged(int value)
        {
            QualitySettings.SetQualityLevel(value);
        }

        private void TimeScaleChanged(float value)
        {
            Time.timeScale = value;
            DOTween.timeScale = value;
            AudioManager.Singleton.SoundEffectPlayer.Pitch = value;
            AudioManager.Singleton.AudioPlayer.Pitch = value;
        }

        protected override void OnDestroy()
        {
            base.OnDestroy();
            TimeScale.OnValueChanged -= TimeScaleChanged;
            Quality.OnValueChanged -= QualityOnOnValueChanged;
            SoundEffectVolume.OnValueChanged -= SoundEffectVolumeOnOnValueChanged;
            AudioVolume.OnValueChanged -= AudioVolumeOnOnValueChanged;
        }
    }
}